
# =================================================================
#
# -*- coding:utf-8 -*-
# @Date: 2020/2/20
# @Author: Tigerots
#
# =================================================================


# 0xA001-RTU 标准CRC16计算
# 输入参数为数字串数组
# 输出为低字节在前,高字节在后
def calc_crc_str(string):
    data = bytearray.fromhex(string)
    crc_temp: int = 0xFFFF
    for pos in data:
        crc_temp ^= pos
        for i in range(8):
            if (crc_temp & 1) != 0:
                crc_temp >>= 1
                crc_temp ^= 0xA001
            else:
                crc_temp >>= 1
    # return hex(((crc & 0xff) << 8) + (crc >> 8))
    # return hex(crc_temp & 0xff), hex(crc_temp >> 8)
    return int(crc_temp & 0xff), int(crc_temp >> 8)

# 0xA001-RTU 标准CRC16计算
# 输入参数为十六进制数组
# 输出为低字节在前,高字节在后
def calc_crc_hex(data):
    crc_temp = 0xFFFF
    for pos in data:
        crc_temp ^= pos
        for i in range(8):
            if (crc_temp & 1) != 0:
                crc_temp >>= 1
                crc_temp ^= 0xA001
            else:
                crc_temp >>= 1
    # return hex(((crc & 0xff) << 8) + (crc >> 8))
    # return hex(crc_temp & 0xff), hex(crc_temp >> 8)
    return int(crc_temp & 0xff), int(crc_temp >> 8)



if __name__ == '__main__':

    crc = calc_crc_str('105100000200514D')
    print(crc)

    sss = [0x10, 0x51, 0x00, 0x00, 0x02, 0x00, 0x51, 0x4D]
    crc = calc_crc_hex(sss)
    print(crc)

